<template>
  <div class="website-info">
    <div class="title">
      <div class="top">
        <SvgIcon name="website" class="svg" />
        <h3>网站信息</h3>
      </div>
      <div class="line"></div>
      <div class="description">
        <span>运行时间：</span>
        <span>{{ data.time }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, watch } from 'vue';
import useWebsiteInfoStore from '@/store/modules/websiteInfo.store.ts';
import { WebsiteInfo } from '@/http/public.type.ts';

const data = reactive({
  websiteInfo: {} as WebsiteInfo,
  time: ''
});

let intervalId: any = null;

onMounted(() => {
  init();
});

onUnmounted(() => {
  clearInterval(intervalId);
});

watch(
  () => useWebsiteInfoStore().websiteInfo,
  () => {
    init();
  }
);

const init = () => {
  data.websiteInfo = useWebsiteInfoStore().websiteInfo as WebsiteInfo;

  intervalId = setInterval(() => {
    data.time = getTimeDiffString(
      parseDateString(data.websiteInfo.runningTime)
    );
  }, 1000);
};

function getTimeDiffString(targetTime: Date): string {
  const currentTime = new Date();
  const timeDiff = Math.abs(currentTime.getTime() - targetTime.getTime());

  const seconds = Math.floor(timeDiff / 1000) % 60;
  const minutes = Math.floor(timeDiff / (1000 * 60)) % 60;
  const hours = Math.floor(timeDiff / (1000 * 60 * 60)) % 24;
  const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

  return `距今${days}天${hours}时${minutes}分${seconds}秒`;
}

function parseDateString(dateString: string): Date {
  const [datePart, timePart] = dateString.split(' ');
  const [year, month, day] = datePart.split('-');
  const [hour, minute, second] = timePart.split(':');

  return new Date(
    parseInt(year),
    parseInt(month) - 1,
    parseInt(day),
    parseInt(hour),
    parseInt(minute),
    parseInt(second)
  );
}
</script>

<style scoped lang="less">
.website-info {
  width: 100%;
  height: 180px;

  box-shadow: var(--crane-ring-offset-shadow, 0 0 #0000),
    var(--crane-ring-shadow, 0 0 #0000), var(--crane-shadow);

  border-radius: 20px;

  position: relative;
  background-color: var(--background-secondary);
  margin-top: 20px;

  .title {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;

    .top {
      display: flex;
      align-items: center;

      .svg {
        width: 20px;
        height: 20px;
      }

      h3 {
        margin-left: 10px;
        margin-top: 10px;
        margin-bottom: 10px;
      }
    }

    .line {
      background: linear-gradient(
        130deg,
        rgb(36, 198, 220),
        rgb(84, 51, 255) 41.07%,
        rgb(255, 0, 153) 76.05%
      );
      width: 60px;
      height: 4px;
      border-radius: 100000px;
    }

    .description {
      width: 100%;
      display: flex;
      color: var(--font-color);
      margin-top: 15px;

      font-size: 14px;
    }
  }
}
</style>
